<template>
  <div class="app-container">
    <div v-if="!isEdit">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <router-link :to="'/mer/list'" class="link-type" v-if="this.restaurant!=1">
            <el-button icon="el-icon-back" size="mini">
              返 回
            </el-button>
          </router-link>

          <router-link :to="'/mer/restaurant'" class="link-type" v-if="restaurant==1">
            <el-button icon="el-icon-back" size="mini">
              返 回
            </el-button>
          </router-link>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                     v-hasPermi="['module:mercoupon:add']">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                     v-hasPermi="['module:mercoupon:edit']">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                     v-hasPermi="['module:mercoupon:remove']">删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="couponList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="商家名称" align="center" prop="merName" width="200"/>
        <el-table-column label="优惠券类型" align="center" prop="couponType" width="130">
          <template slot-scope="scope">
            <div>
              <el-tag v-if="scope.row.couponType === 0" :type="''">线上抵扣券</el-tag>
              <el-tag v-else-if="scope.row.couponType === 1" :type="'success'">线下抵扣券</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="优惠券名称" align="center" prop="couponName" width="150"/>
        <el-table-column label="购买价格" align="center" prop="price" />
        <el-table-column label="抵扣价格" align="center" prop="dikouPrice" />
        <el-table-column label="分佣比例" align="center" prop="subRate" />
        <el-table-column label="当前销量" align="center" prop="sales" />
        <el-table-column label="有效期的类型" align="center" prop="validateType" width="100">
          <template slot-scope="scope">
            <div>
              <el-tag v-if="scope.row.validateType === 0" :type="''">限制时间</el-tag>
              <el-tag v-else-if="scope.row.validateType === 1" :type="'success'">不限制时间</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="有效期的开始时间" align="center" prop="beginTime" width="150">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.beginTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="有效期的结束时间" align="center" prop="endTime" width="150">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="state">
          <template slot-scope="scope">
            <div>
              <el-tag v-if="scope.row.state === 0" :type="'info'">下架</el-tag>
              <el-tag v-else-if="scope.row.state === 1" :type="'success'">上架</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="120">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                       v-hasPermi="['module:mercoupon:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['module:mercoupon:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0"
                  :total="total"
                  :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize"
                  @pagination="getList" />
    </div>

    <!-- 添加或修改商家抵扣券对话框 -->
    <div v-if="isEdit">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="优惠券名称" prop="couponName">
          <el-input v-model="form.couponName" placeholder="请输入优惠券名称" size="mini"/>
        </el-form-item>
        <el-form-item label="优惠券类型" prop="couponType">
          <el-radio-group v-model="form.couponType" size="mini">
            <el-radio :value="0" :label="0">线上抵扣券</el-radio>
            <el-radio :value="1" :label="1">线下抵扣券(凌云家电)</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-row>
          <el-col :span="6">
            <el-form-item label="抵扣券购买价格" prop="price">
              <el-input v-model="form.price" placeholder="请输入抵扣券的购买价格" size="mini">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="抵扣的价格" prop="dikouPrice">
              <el-input v-model="form.dikouPrice" placeholder="请输入抵扣的价格" size="mini">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>

          <el-col :span="6">
            <el-form-item label="抵扣券分佣比例" prop="subRate">
              <el-input v-model="form.subRate" placeholder="请输入抵扣券的分佣比例" size="mini">
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="当前销量" prop="sales">
              <el-input v-model="form.sales" type="number" placeholder="请输入当前销量" size="mini">
                <template slot="append"></template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>


        <el-form-item label="抵扣类型" prop="isAll">
          <el-radio-group v-model="form.isAll" size="mini">
            <el-radio :value="0" :label="0">限制商品抵扣</el-radio>
            <el-radio :value="1" :label="1">全部可以抵扣</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="可抵扣商品" prop="merProductIds" v-if="form.isAll === 0">
          <el-checkbox-group v-model="form.merProductIds" size="mini" @change="checkMerProduct">
            <el-checkbox v-for="pro in merProductList" :label="pro.id" :key="pro.id">
              <el-card :body-style="{ padding: '10px', }">
                <img :src="pro.imagePath" class="image" style="height:100px;">
                <div style="padding: 5px 15px;">
                  <el-row>
                    <span>{{pro.storeName}}</span>
                  </el-row>
                  <el-row>
                    <span>{{pro.storeInfo}}</span>
                  </el-row>
                </div>
              </el-card>
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="form.state" size="mini">
            <el-radio :value="1" :label="1">上架</el-radio>
            <el-radio :value="0" :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-row>
          <el-col :span="6">
            <el-form-item label="有效期类型" prop="validateType">
              <el-radio-group v-model="form.validateType" size="mini">
                <el-radio :value="0" :label="0">限制时间</el-radio>
                <el-radio :value="1" :label="1">不限制时间</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="有效期开始时间" prop="beginTime" v-if="form.validateType == 0">
              <el-date-picker clearable size="mini" v-model="form.beginTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="选择有效期的开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="有效期结束时间" prop="endTime" v-if="form.validateType == 0">
              <el-date-picker clearable size="mini" v-model="form.endTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="选择有效期的结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="图标" prop="imgUrlPath" >
              <single-pic v-model="form.imgUrlPath" type="image" @handleChecked="chooseImg" :uploadType="2"
                          :num="1" :width="120" :height="120" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="购买须知" prop="buyingTips">
              <editor v-model="form.buyingTips" :min-height="120" size="mini"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="产品描述" prop="remark">
              <editor v-model="form.remark" :min-height="120" size="mini"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="isEdit = false" size="mini">取 消</el-button>
      </div>
    </div>
  </div>
</template>

<script>
  import { listCoupon, getCoupon, delCoupon, addCoupon, updateCoupon, exportCoupon } from "@/api/module/mer/coupon";

  import {listProductByMerId } from "@/api/module/product/list";
  import singlePic from '@/components/SingleMaterial';

  import { listMerCouponProduct } from "@/api/module/mer/couponProduct";
  import Template from "../wx/template";

  export default {
    name: "Coupon",
    components: {Template,singlePic},
    data() {
      return {
        isEdit:false,
        // 按钮loading
        buttonLoading: false,
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 商家抵扣券表格数据
        couponList: [],
        merChooseProducts:[],
        merProductList:[],
        // 弹出层标题
        title: "",
        restaurant:0,
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          merId: undefined,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
        }
      };
    },
    created() {
      this.restaurant = this.$route.query.restaurant ? this.$route.query.restaurant : 0;
      console.log('mer/coupon  this.$route.query',this.$route.query);
      if(this.$route.query.merId){
        this.queryParams.merId = this.$route.query.merId ? this.$route.query.merId : 0;
        this.form.merId = this.$route.query.merId ? this.$route.query.merId : 0;
      }
      this.getList();
      this.getMerProduct();
    },
    activated() {
      console.log('mer/coupon  this.$route.query',this.$route.query);
      if(this.$route.query.merId){
        this.queryParams.merId = this.$route.query.merId ? this.$route.query.merId : 0;
        this.form.merId = this.$route.query.merId ? this.$route.query.merId : 0;
      }
      this.getList();
    },
    methods: {
      /** 查询商家抵扣券列表 */
      getList() {
        this.loading = true;
        listCoupon(this.queryParams).then(response => {
          this.couponList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      checkMerProduct(val){
        console.log('checkMerProduct',val);
        this.form.merProductIds = val;
      },
      getMerProduct(){
        this.loading = true;
        var that = this;
        listProductByMerId(that.form.merId).then(response => {
          that.merProductList = response.data;
        });
      },
      chooseImg(data){
        console.log("menu chooseImg",data);
        if(data.length > 0) {
          this.form.imgUrlPath = data[0].imgUrl;
          this.form.imgUrl = data[0].url;
        }
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          merId: this.queryParams.merId,
          couponType:undefined,
          couponName: undefined,
          price: undefined,
          dikouPrice: undefined,
          subRate: undefined,
          createTime: undefined,
          validateType: undefined,
          beginTime: undefined,
          endTime: undefined,
          state: undefined,
          buyingTips: undefined,
          remark: undefined,
          isAll:0,
          sales:undefined,
          imgUrl:undefined,
          imgUrlPath:undefined,
          merProductIds:[],
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
        this.single = selection.length!==1;
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.isEdit = true;
        this.title = "添加商家抵扣券";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.loading = true;
        this.reset();
        const id = row.id || this.ids;
        var that = this;
        that.form.merProductIds = [];
        getCoupon(id).then(response => {
          this.loading = false;
          this.form = response.data;
          that.merChooseProducts = response.data.merProducts;
          console.log("that.merChooseProducts",that.merChooseProducts);

          var ids = [];
          for (var index in that.merChooseProducts){
            console.log('that.merChooseProducts[index].id',that.merChooseProducts[index].id);
            ids.push(that.merChooseProducts[index].id);
          }
          that.form.merProductIds = ids;
          this.isEdit = true;
          this.title = "修改商家抵扣券";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.buttonLoading = true;

            if (this.form.id != null) {
              updateCoupon(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.isEdit = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            } else {
              addCoupon(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.isEdit = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除商家抵扣券编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.loading = true;
          return delCoupon(ids);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有商家抵扣券数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportCoupon(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
      }
    }
  };
</script>
